
package log;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * The output class that print message to the specified terminal.
 * 
 * @author TCSS 558 Team 6
 * @version Spring 2013
 */
public class Log
{

  /** The default new line String. */
  public static final String NEWLINE = "\r\n";

  /** The default tab string */
  public static final String TAB = "\t";

  /** It is the output to write thing to the file. */
  private final OutputStream my_writer;

  /**
   * Creates a new OutPutStream with the specified output destination.
   * 
   * @param the_file is the file name for the output.
   * @throws IOException if there is a problem open the file.
   */
  public Log(final String the_file) throws IOException
  {

    // check if BufferedReader is required here -
    // writer = new BufferedWriter(new OutputStreamWriter(
    // new FileOutputStream("GameLog.txt", true), "utf-8"));
    // writer.write(outputString + "\r\n");
    // see the synchronized example code here
    // http://stackoverflow.com/questions/10568932/synchronizing-file-output-in-a-static-class

    my_writer = new FileOutputStream(the_file/* , true */);
  }

  /**
   * Prints out the message to the output stream.
   * 
   * @param the_message is the message to be printed.
   */
  public synchronized void out(final String the_message)
  {
    try
    {
      my_writer.write(the_message.getBytes(Charset.forName("US-ASCII")));

      my_writer.write(NEWLINE.getBytes());
    }
    catch (final IOException e)
    {

      e.printStackTrace();
    }
  }

  /**
   * Prints out an array of output strings. And each line has 10 strings
   * 
   * @param the_table is the array of output strings.
   */
  public void printTable(final Object[] the_table)
  {
    final int length = the_table.length;
    int j;
    for (int i = 0; i != length; i += j)
    {
      final StringBuffer sb = new StringBuffer();
      j = 0;
      for (; (j != 10) && (i + j != length); ++j)
      {
        sb.append(the_table[i + j] + TAB);
      }
      this.out(sb.toString());
    }
  }

}
